
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.linear_model as lm
import sklearn.metrics as sm

data = pd.read_csv('../data_test/Salary_Data2.csv')
train_x = data.iloc[:,:-1]
train_y = data.iloc[:,-1]
model = lm.LinearRegression() #构建模型

model.fit(train_x,train_y) #训练模型
pred_train_y = model.predict(train_x) #预测模型


# 创建岭回归器并进行训练
model_ridge = lm.Ridge(alpha=100)
model_ridge.fit(train_x,train_y)
pred_train_y_ridge = model_ridge.predict(train_x)

plt.plot(train_x,pred_train_y,c='orangered')
plt.plot(train_x,pred_train_y_ridge,c='purple')
plt.scatter(data['YearsExperience'],data['Salary'],s=50)
# plt.show()

#调整岭回归模型参数
test_x = train_x.iloc[:30:4]
test_y = train_y[:30:4]
# pred_test_y = model_ridge.predict(test_x)
# print(sm.r2_score(test_y, pred_test_y))

params = np.arange(50,150,10)
scores=[]
for param in params:
    model_ridge = lm.Ridge(alpha=param)
    model_ridge.fit(train_x,train_y)
    pred_test_y=model_ridge.predict(test_x)
    r2 = sm.r2_score(test_y,pred_test_y)
    scores.append(r2)

df = pd.DataFrame(scores,index=params)
print(df)
print('最好的模型参数：',df.idxmax().values)
